//
//  AlbumViewController.m
//  OntheRoadV4
//
//  Created by ZhangYanhua on 14/11/21.
//  Copyright (c) 2014年 EricHuang. All rights reserved.
//

#import "AlbumViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "MyAlbumLocation.h"
#import "QWSeparatorViews.h"
#import "NSDate-Utilities.h"
#import "ALAssetsLibrary+CustomPhotoAlbum.h"
#import "ALAssetsGroupEnumerator.h"
#import "AlbumViewDataSource.h"
#import "AlbumViewDataSource_iOS8.h"
#import "AlbumViewDataSourceProtocol.h"
#import "QWImageMangerConfig.h"

@interface AlbumViewController () {
    
    BOOL showAlbumTableView;
    NSInteger maxImageCnt;
    BOOL canAccessCamera;
    BOOL hasVideoDevice;
    NSInteger imagesPerRow;
    BOOL showPhotos;
}

@property (nonatomic, strong) id<AlbumViewDataSourceProtocol> dataSource;

@end

@implementation AlbumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:[QWImageMangerConfig baseBundle]];
    if (self) {
        
        canAccessCamera = [ALAssetsGroupEnumerator hasPermissionToAccessCameraAndAlert:NO];
        
        hasVideoDevice = ([[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count] > 0);
    }
    return self;
}

- (id)initWithMaxImageCnt:(NSInteger)maxCnt forPhotos:(BOOL)forPhotos
{
    self = [super init];
    if (self) {
        showPhotos = forPhotos;
        
        if (NSClassFromString(@"PHPhotoLibrary")) {
            _dataSource = [[AlbumViewDataSource_iOS8 alloc] initWithTableViewController:self
                                                                            maxImageCnt:maxCnt
                                                                             shwoPhotos:showPhotos];
        } else {
            _dataSource = [[AlbumViewDataSource alloc] initWithTableViewController:self
                                                                       maxImageCnt:maxCnt
                                                                        shwoPhotos:showPhotos];
        }
    }
    return self;
}

- (void)dealloc
{
 
    if (self.captureManager) {
        [self.captureManager setDelegate:nil];
        [self.captureManager.positionIntervalTimer invalidate];
        [self.captureManager.positioningTimer invalidate];
        [self.captureManager removeObservrs];
    }
}

- (void)cancelBtnPressed:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(didCancelAlbumPickerAnimated:)]) {
        [self.delegate didCancelAlbumPickerAnimated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)doneBtnPressed:(id)sender
{
    if ([self.dataSource.selectedAssets count] == 0 &&
        [self.delegate respondsToSelector:@selector(didSkipCamera)]) {
        [self.delegate didSkipCamera];
    } else if ([self.delegate respondsToSelector:@selector(didFinishPickingImageAssets:)]) {
        [self.delegate didFinishPickingImageAssets:self.dataSource.selectedAssets];
    } else {
        [self cancelBtnPressed:nil];
    }
}

#pragma mark -
#pragma mark access permission

- (CABasicAnimation *)getPreviewLayerAnimation
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(50.0f, 50.0f)];
    animation.duration = 0.3f;
    animation.removedOnCompletion = NO;
    
    return animation;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    [self.view setBackgroundColor:[UIColor whiteColor]];

    self.albumTableView.dataSource = self.dataSource;
    self.albumTableView.delegate = self.dataSource;
    self.tableView.dataSource = self.dataSource;
    self.tableView.delegate = self.dataSource;
    self.bgTitleLabel.textColor = LABEL_TEXT_COLOR_GRAY;
    self.bgSubTitleLabel.textColor = LABEL_TEXT_COLOR_GRAY;
    self.bgVideoLabel.textColor = LABEL_TEXT_COLOR_GRAY;
    
    self.navTitleLabel.textColor = [UIColor whiteColor];
    self.navSubTitleLabel.textColor = [UIColor colorWithWhite:1.0f alpha:0.7];
    [self.navTitleView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(tapOnNavTitleView:)]];
    self.albumMaskView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.4f];
    self.albumMaskView.alpha = 0.0f;
    self.albumTableView.alpha = 0.0f;
    self.albumTableView.translatesAutoresizingMaskIntoConstraints = NO;
    
    self.albumTableView.contentInset = self.tableView.contentInset;
    self.albumTableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.albumTableView.contentOffset = CGPointMake(0.0f, -self.tableView.contentInset.top);
    self.navDropArrow.image = [QWImageMangerConfig imageNamed:@"navDropArrow.png"];
    self.navDropArrow.transform = CGAffineTransformMakeRotation(0);
    
    [self.albumMaskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                     action:@selector(hideAlbumTableView)]];
    
    self.navigationItem.leftBarButtonItem = [self allocAndInitWithTitle:QWImagePickerLocalizedString(@"Cancel", nil)
                                                                            target:self
                                                                            action:@selector(cancelBtnPressed:)
                                                                            isLeft:YES];
    
    if (showPhotos) {
        self.navigationItem.rightBarButtonItem = [self allocAndInitWithTitle:QWImagePickerLocalizedString(@"Skip", nil)
                                                                                 target:self
                                                                                 action:@selector(doneBtnPressed:)
                                                                                 isLeft:NO];
    }
    
    [self updateNavBarTitleView];
    
    if (!canAccessCamera) {
        NSDate *lastAlertDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"QWImagePickerNoPermissionAlertDate"];
        if (!lastAlertDate || [[NSDate date] timeIntervalSinceDate:lastAlertDate] > 5 * 24 * 60 * 60) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"QWImagePickerNoPermissionAlertDate"];
            
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:QWImagePickerLocalizedString(@"This app does not have access to your camera!", nil)
                                                             message:QWImagePickerLocalizedString(@"You can enable access in Privacy Settings.", nil)
                                                            delegate:nil
                                                   cancelButtonTitle:QWImagePickerLocalizedString(@"I know", nil)
                                                   otherButtonTitles:nil];
            [alert show];
        }
    }
    
    if ([self captureManager] == nil && canAccessCamera && showPhotos && hasVideoDevice) {
        AVCamCaptureManager *manager = [[AVCamCaptureManager alloc] init];
        [self setCaptureManager:manager];
        
        if ([[self captureManager] setupSession]) {
            // Create video preview layer and add it to the UI
            AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]];
            
            [newCaptureVideoPreviewLayer setBackgroundColor:[UIColor blackColor].CGColor];
            
            [newCaptureVideoPreviewLayer addAnimation:[self getPreviewLayerAnimation] forKey:@"position"];
            
            if ([[[self captureManager] session] canSetSessionPreset:AVCaptureSessionPreset352x288]) {
                self.captureManager.session.sessionPreset = AVCaptureSessionPreset352x288;
            } else {
                self.captureManager.session.sessionPreset = AVCaptureSessionPresetLow;
            }
            
            if ([newCaptureVideoPreviewLayer respondsToSelector:@selector(connection)]) {
                if ([[newCaptureVideoPreviewLayer connection] isVideoOrientationSupported]) {
                    [[newCaptureVideoPreviewLayer connection] setVideoOrientation:AVCaptureVideoOrientationPortrait];
                }
            } else {
                if ([newCaptureVideoPreviewLayer isOrientationSupported]) {
                    [newCaptureVideoPreviewLayer setOrientation:AVCaptureVideoOrientationPortrait];
                }
            }
            
            [newCaptureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
            
            [self setPreviewLayer:newCaptureVideoPreviewLayer];
            
            // Start the session. This is done asychronously since -startRunning doesn't return until the session is running.

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[[self captureManager] session] startRunning];
            });
        }
    }
    

    
    [self.dataSource loadLastAlbum];
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if ([[[self captureManager] session] canSetSessionPreset:AVCaptureSessionPreset352x288]) {
        self.captureManager.session.sessionPreset = AVCaptureSessionPreset352x288;
    } else {
        self.captureManager.session.sessionPreset = AVCaptureSessionPresetLow;
    }
    
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (cell) {
        AlbumPhotoCell *assetCell = (AlbumPhotoCell *)cell;
        
        UIView *view = [[assetCell imageViews] firstObject];
        CALayer *viewLayer = [view layer];
        [viewLayer setMasksToBounds:YES];
        
        CGRect bounds = [view bounds];
        [self.previewLayer setFrame:bounds];
        
        [self.previewLayer addAnimation:[self getPreviewLayerAnimation] forKey:@"position"];
        
        [viewLayer addSublayer:self.previewLayer];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (id)allocAndInitWithTitle:(NSString *)title target:(id)target action:(SEL)action isLeft:(BOOL)isLeft
{
    UIButton *btn;
    CGFloat  btnImageInset;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn setTintColor:[UIColor whiteColor]];
        btnImageInset = 8.0f;
    } else {
        btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btnImageInset = 0.0f;
        [btn setTitleColor:RGB(127, 195, 254) forState:UIControlStateDisabled];
    }
    
    [btn setFrame:CGRectMake(0.0f, 0.0f, 64.0f, 44.0f)];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    if (isLeft) {
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0.0f, -btnImageInset, 0.0f, btnImageInset)];
        [[btn titleLabel] setFont:CUSTOM_FONT_LIGHT(17.0f)];
    } else {
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0.0f, btnImageInset, 0.0f, -btnImageInset)];
        [[btn titleLabel] setFont:CUSTOM_FONT_LIGHT(17.0f)];
    }
    [btn setTitle:title forState:UIControlStateNormal];
    [btn sizeToFit];
    
    return [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)updateNavBarTitleView
{
    NSString *navTitle = showPhotos ? QWImagePickerLocalizedString(@"Add photos", nil) : QWImagePickerLocalizedString(@"Add videos", nil);
    if ([self.dataSource.selectedGroupName length]) {
        self.navTitleLabel.text = navTitle;
        self.navSubTitleLabel.text = self.dataSource.selectedGroupName;
        self.navigationItem.titleView = self.navTitleView;
    } else {
        self.navigationItem.title = navTitle;
        self.navigationItem.titleView = nil;
    }
    
    if (showPhotos) {
        UIButton *rightBtn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
        if ([rightBtn isKindOfClass:[UIButton class]]) {
            if ([self.dataSource.selectedAssets count] == 0) {
                self.navigationItem.rightBarButtonItem = [self allocAndInitWithTitle:QWImagePickerLocalizedString(@"Skip", nil)
                                                                                         target:self
                                                                                         action:@selector(doneBtnPressed:)
                                                                                         isLeft:NO];
            } else {
                NSString *titleStr = [NSString stringWithFormat:QWImagePickerLocalizedString(@"Next(%d)", nil), self.dataSource.selectedAssets.count];
                self.navigationItem.rightBarButtonItem = [self allocAndInitWithTitle:titleStr
                                                                                         target:self
                                                                                         action:@selector(doneBtnPressed:)
                                                                                         isLeft:NO];
            }
        }
    }
}

- (void)tapOnNavTitleView:(UIGestureRecognizer *)recg
{
    if (showAlbumTableView) {
        [self hideAlbumTableView];
    } else {
        [self showAlbumTableView];
    }
}

- (void)hideAlbumTableView
{
    showAlbumTableView = NO;
    
    [self.navigationItem.leftBarButtonItem setEnabled:YES];
    [self.navigationItem.rightBarButtonItem setEnabled:YES];
    
    [UIView animateWithDuration:0.30f
                          delay:0.0f
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         self.albumMaskView.alpha = 0.0f;
                         self.albumTableView.alpha = 0.0f;
                         
                         self.navDropArrow.transform = CGAffineTransformMakeRotation(0);
                         
                         CGFloat tableHeight = self.albumTableView.frame.size.height;
                         self.albumTopSpaceConstraint.constant = -tableHeight;
                         [self.albumTableView layoutIfNeeded];
                     } completion:^(BOOL finished) {
                     }];
}

- (void)showAlbumTableView
{
    showAlbumTableView = YES;
    
    [self.navigationItem.leftBarButtonItem setEnabled:NO];
    [self.navigationItem.rightBarButtonItem setEnabled:NO];
    
    self.albumTableView.contentInset = self.tableView.contentInset;
    
    [UIView animateWithDuration:0.30f
                          delay:0.0f
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         self.albumMaskView.alpha = 1.0f;
                         self.albumTableView.alpha = 1.0f;
                         
                         self.navDropArrow.transform = CGAffineTransformMakeRotation(-M_PI);
                         
                         NSInteger maxNum = [UIScreen mainScreen].bounds.size.height / 60.0f;
                         maxNum = MIN(maxNum / 2 + 2, [self.dataSource numberOfAssetsGroup]);
                         CGFloat albumHeight = maxNum * 60.0f + 10.0f + self.albumTableView.contentInset.top;
                         self.albumHeightConstraint.constant = albumHeight;
                         
                         self.albumTopSpaceConstraint.constant = 0.0f;
                         
                         [self.albumTableView layoutIfNeeded];

                         NSUInteger index = [self.dataSource indexOfSelectedGroup];
                         if (index != NSNotFound && [self.dataSource numberOfAssetsGroup]) {
                             [self.albumTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
                                                        atScrollPosition:UITableViewScrollPositionTop
                                                                animated:NO];
                         }
                     } completion:^(BOOL finished) {
                     }];
}



- (void)takeAPicture:(id)assetURL
{
    [self.dataSource takeAPicture:assetURL];
}

- (void)resetCaptureVideoPreviewLayer
{

}

#pragma mark -
#pragma mark EditVideoViewControllerDelegate

- (void)didFinishEditVideoWithInfoDict:(NSDictionary *)infoDict
{
    if (!infoDict &&
        [self.delegate respondsToSelector:@selector(didSkipCamera)]) {
        [self.delegate didSkipCamera];
    } else if ([self.delegate respondsToSelector:@selector(didFinishPickingVideoWithDict:)]) {
        [self.delegate didFinishPickingVideoWithDict:infoDict];
    } else {
        [self cancelBtnPressed:nil];
    }
}

@end
